package ezXpns.cloud;

import ezXpns.BudgetChange;
import ezXpns.Tag;
import ezXpns.storage.Storage;
import java.util.TreeMap;
import java.util.UUID;
import java.util.Map.Entry;

/**
 * Search through the storage to find all the tags and their 
 * relative ratio to the tag with the highest value.
 *
 */

//@author A0086934R
public class CloudManager {

	/**
	 * creates the CloudManager
	 * 
	 * @param searcher the searcher used to search through the storage
	 * @param storage the storage from which data is to be drawn from
	 */
	public CloudManager(Storage<BudgetChange> storage){
		this.storage = storage;
	}
	/**
	 * Generates and returns a normalized TreeMap<String, Float> 
	 * of tags and its respective total value as a ratio of the 
	 * largest value of any tag
	 * 
	 * @return normalizedTree, which is a TreeMap<String, Float> of Tag-Ratio map.
	 *  Ratio ranges from 0.00 to 1.00, with 1.00 being the largest value
	 * in the TreeMap
	 */
	public TreeMap<String, Float> generateNormalizedCloud() {
		generateCloud();
		normalizeCloud();
		return normalizedTree;
	}
	
	/**
	 * searches through the storage for all tags and calculate the total
	 * value for each tag
	 */
	private void generateCloud(){
		cloudTree.clear();
		for(Entry<UUID, BudgetChange> itemPair : storage.getAllEntries()){
			for(Tag itemTag : itemPair.getValue().getAllTags()){
				if(!cloudTree.containsKey(itemTag)) {
					cloudTree.put(itemTag.getName(), (float)0);
				}
				cloudTree.put(itemTag.getName(), 
						(cloudTree.get(itemTag).floatValue() + itemPair.getValue().getAmount()));
			}
		}
	}
	
	/**
	 * normalize the values of each of the tags as a ratio. 
	 * Each tag will be associated with a float value
	 * between 0.00 to 1.00, with 1.00 being the largest
	 * value in the collection
	 */
	private void normalizeCloud() {
		normalizedTree.clear();
		normal = 0;
		for(float value : cloudTree.values()) {
			if(value > normal){
				normal = value;
			}
		}
		for(String tag : cloudTree.keySet()) {
			if(normal <= 0) {
				normalizedTree.put(tag, (float)0);
				continue;
			}
			normalizedTree.put(tag, cloudTree.get(tag).floatValue()/normal);
		}
	}
	
	private Storage<BudgetChange> storage;
	private TreeMap<String, Float> cloudTree = new TreeMap<String, Float>();
	private TreeMap<String, Float> normalizedTree = new TreeMap<String, Float>();
	private float normal = 0;
}
